from marshmallow import Schema, fields, validate, validates, ValidationError
from datetime import datetime

class MedicalOrderItemSchema(Schema):
    """医嘱项目模式"""
    type = fields.Str(required=True, validate=validate.OneOf(['药品', '检验', '检查', '治疗', '护理', '饮食', '其他']))
    content = fields.Str(required=True)
    frequency = fields.Str()
    duration = fields.Str()
    startTime = fields.DateTime()
    endTime = fields.DateTime()
    note = fields.Str()

class ExecutionSchema(Schema):
    """医嘱执行模式"""
    executedBy = fields.Str()
    executedAt = fields.DateTime()
    note = fields.Str()

class StopSchema(Schema):
    """医嘱停止模式"""
    stoppedBy = fields.Str()
    stoppedAt = fields.DateTime()
    reason = fields.Str()

class MedicalOrderSchema(Schema):
    """医嘱模式"""
    orderId = fields.Str()
    patientId = fields.Str(required=True)
    doctorId = fields.Str(required=True)
    departmentId = fields.Str()
    visitId = fields.Str()
    medicalRecordId = fields.Str()
    type = fields.Str(required=True, validate=validate.OneOf(['长期医嘱', '临时医嘱']))
    items = fields.List(fields.Nested(MedicalOrderItemSchema), required=True)
    frequency = fields.Str()
    startTime = fields.DateTime()
    endTime = fields.DateTime()
    status = fields.Str(validate=validate.OneOf(['已开立', '已执行', '已停止']), dump_default='已开立')
    execution = fields.Nested(ExecutionSchema)
    stop = fields.Nested(StopSchema)
    priority = fields.Str(validate=validate.OneOf(['常规', '加急', '紧急']), dump_default='常规')
    note = fields.Str()
    createdAt = fields.DateTime(dump_default=datetime.utcnow)
    updatedAt = fields.DateTime(dump_default=datetime.utcnow)

class MedicalOrderUpdateSchema(Schema):
    """医嘱更新模式"""
    patientId = fields.Str()
    doctorId = fields.Str()
    departmentId = fields.Str()
    visitId = fields.Str()
    medicalRecordId = fields.Str()
    type = fields.Str(validate=validate.OneOf(['长期医嘱', '临时医嘱']))
    items = fields.List(fields.Nested(MedicalOrderItemSchema))
    frequency = fields.Str()
    startTime = fields.DateTime()
    endTime = fields.DateTime()
    status = fields.Str(validate=validate.OneOf(['已开立', '已执行', '已停止']))
    priority = fields.Str(validate=validate.OneOf(['常规', '加急', '紧急']))
    note = fields.Str()

class MedicalOrderQuerySchema(Schema):
    """医嘱查询模式"""
    patientId = fields.Str()
    doctorId = fields.Str()
    departmentId = fields.Str()
    type = fields.Str(validate=validate.OneOf(['长期医嘱', '临时医嘱', 'all']))
    status = fields.Str(validate=validate.OneOf(['已开立', '已执行', '已停止', 'all']))
    startDate = fields.Date()
    endDate = fields.Date()
    priority = fields.Str(validate=validate.OneOf(['常规', '加急', '紧急', 'all']))

class ExecuteOrderSchema(Schema):
    """执行医嘱模式"""
    note = fields.Str()

class StopOrderSchema(Schema):
    """停止医嘱模式"""
    reason = fields.Str(required=True) 